package itman.elm.utils;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.net.URLDecoder;
import java.net.URLEncoder;

public class CookieUtil {

    private HttpServletRequest request;
    private HttpServletResponse response;

    public CookieUtil(HttpServletRequest request, HttpServletResponse response) {
        super();
        this.request = request;
        this.response = response;
    }

    public void saveOrUpdate(String cookieName, String cookieValue, int maxAge) {
        try{
            cookieValue = URLEncoder.encode(cookieValue, "utf-8");
            Cookie cookie = new Cookie(cookieName, cookieValue);
            cookie.setMaxAge(maxAge);
            response.addCookie(cookie);

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public String getValue(String cookieName){
        String cookieValue = null;
        try{
            Cookie[] cookies = request.getCookies();

            if (cookies != null){
                for (Cookie cookie : cookies){
                    if(cookie.getName().equals(cookieName)){
                        cookieValue = URLDecoder.decode(cookie.getValue(), "utf-8");
                        break;
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return cookieValue;
    }

    public void delete(String cookieName){
        // 创建 Cookie 对象
        Cookie cookie = new Cookie(cookieName, null);

        cookie.setMaxAge(0);

        // 将 Cookie 响应回客户端
        response.addCookie(cookie);
    }
}
